package com.whc.task;

import com.whc.constant.RedisHeader;
import com.whc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 韦红材
 * @ClassName OnlineTask
 * @data 2024/12/19 08:49
 * @Version V1.0
 **/
@Component
@Slf4j
public class OnlineTask {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    //每六十秒看一下是否还存活
    public void isOnline(){
        List<Integer> allUserId = userService.getAllUserId();
        for(int o:allUserId){

            if(redisTemplate.hasKey(RedisHeader.userOnline+o)){

                String lastTimeS=(String)redisTemplate.opsForValue().get(RedisHeader.userOnline+o);
                log.info("用户"+o+"上一次存活时间"+lastTimeS);
                LocalDateTime lastTime=LocalDateTime.parse(lastTimeS, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if(LocalDateTime.now().isAfter(lastTime.plusMinutes(1))){
                    redisTemplate.delete(RedisHeader.userOnline+o);
                }
            }
        }
    }

}
